using Manon.Admin.Web.Common;
using Manon.Admin.Web.Domain.Entities;
using Manon.Core.Commons;
using Manon.Core.Filters;
using Manon.Core.IOC;
using Manon.Repository;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add<ApiResultFilter>();
    options.Filters.Add<ApiActionFilter>();
    options.Filters.Add<ApiExceptionAsyncFilter>();

}).AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
    options.JsonSerializerOptions.Converters.Add(new LongConverter());
});
 
builder.Services.AddRouting(options =>
   options.LowercaseUrls = true
); 

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddAuthentication(options =>
{

    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(jwtOptions =>
{
    jwtOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.SecretKey)),
        ValidIssuer = AppSettings.Issuer,
        ValidAudience = AppSettings.Audience,
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero

    };
});

builder.Services.AddUnitOfWorkService<AdminDbContext>(options =>
{
    options.UseMySql("server=127.0.0.1;port=3306;userid=root;password=123456;database=test;TreatTinyAsBoolean=false;Persist Security Info=True;", new MySqlServerVersion(new Version(8, 0, 29)));
});

builder.Services.RegisterServices("Manon.Admin.Web");



var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
} 

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
 
 
app.UseAuthentication();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
